<template>
  <div class="netdisk-share">
    <!-- 顶部提示信息 -->
    <div class="share-tip">
      <el-icon class="tip-icon">
        <InfoFilled />
      </el-icon>
      <span>链接分享（分享失效超过1年以上的链接记录将自动清理）</span>
    </div>

    <!-- 分享统计和操作区 -->
    <div class="share-header">
      <div class="share-stats">
        <div class="stat-item">
          <span class="stat-label">全部文件</span>
          <span class="stat-count">已全部加载，共<span class="highlight">{{ shareList.length }}</span>个</span>
        </div>
      </div>
      <div class="share-actions">
        <el-button v-if="selectedItems.length > 0" type="danger" size="small" @click="handleBatchCancel">
          批量取消分享
        </el-button>
      </div>
    </div>

    <!-- 文件列表区域 -->
    <div class="share-content">
      <!-- 表格视图 -->
      <div class="share-table">
        <el-table 
          :data="shareList" 
          style="width: 100%" 
          @selection-change="handleSelectionChange"
          v-loading="loading">
          <el-table-column type="selection" width="55" />
          <el-table-column label="分享文件" min-width="200">
            <template #default="scope">
              <div class="file-info">
                <FileTypeIcon :fileType="scope.row.fileType" />
                <span class="file-name">{{ scope.row.fileName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="shareTime" label="分享时间" width="180" />
          <el-table-column label="状态" width="120">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)" size="small">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="visitCount" label="浏览次数" width="100" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <div class="action-buttons">
                <el-button 
                  v-if="scope.row.status === 'active' || scope.row.status === 'expiring_soon'" 
                  link 
                  type="primary" 
                  size="small" 
                  @click="handleCopyLink(scope.row)">
                  <el-icon><Link /></el-icon>
                  复制链接
                </el-button>
                <el-button 
                  v-if="scope.row.status === 'active' || scope.row.status === 'expiring_soon'" 
                  link 
                  type="warning" 
                  size="small" 
                  @click="handleCancelShare(scope.row)">
                  取消分享
                </el-button>
                <span 
                  v-if="scope.row.status === 'expired'" 
                  class="expired-text">
                  链接已失效
                </span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        layout="total, prev, pager, next, jumper"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoFilled, Link } from '@element-plus/icons-vue'
import FileTypeIcon from '~/components/FileTypeIcon.vue'

// ==================== 状态定义 ====================
const loading = ref(false)
const selectedItems = ref([]) // 选中的项目

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 分享列表数据
const shareList = ref([])

// ==================== 生命周期 ====================
onMounted(() => {
  loadShareList()
})

// ==================== 数据加载 ====================
// 加载分享列表
const loadShareList = async () => {
  loading.value = true
  
  // 模拟加载延迟
  await new Promise(resolve => setTimeout(resolve, 300))
  
  // 静态数据
  const mockData = [
    {
      fileId: '1',
      fileName: '应用案例.zip',
      fileType: 'zip',
      shareTime: '2025-10-24 10:50',
      status: 'active',
      visitCount: 1,
      shareUrl: 'https://example.com/share/abc123'
    },
    {
      fileId: '2', 
      fileName: '应用案例.zip',
      fileType: 'zip',
      shareTime: '2025-10-24 10:49',
      status: 'expiring_soon', // 23小时后过期
      visitCount: 11,
      shareUrl: 'https://example.com/share/def456'
    },
    {
      fileId: '3',
      fileName: 'app_logo.png.jpeg',
      fileType: 'image',
      shareTime: '2025-10-24 09:47',
      status: 'expiring_soon', // 23小时后过期
      visitCount: 11,
      shareUrl: 'https://ex  ample.com/share/ghi789'
    },
    {
      fileId: '4',
      fileName: 'apps',
      fileType: 'folder',
      shareTime: '2025-06-13 21:34',
      status: 'expired', // 已过期
      visitCount: 9,
      shareUrl: 'https://example.com/share/jkl012'
    },
    {
      fileId: '5',
      fileName: 'apps',
      fileType: 'folder', 
      shareTime: '2025-06-13 21:33',
      status: 'expired', // 已过期
      visitCount: 0,
      shareUrl: 'https://example.com/share/mno345'
    },
    {
      fileId: '6',
      fileName: '项目文档.pdf',
      fileType: 'pdf',
      shareTime: '2025-10-23 15:30',
      status: 'expired', // 已过期
      visitCount: 25,
      shareUrl: 'https://example.com/share/pqr678'
    },
    {
      fileId: '7',
      fileName: '演示视频.mp4',
      fileType: 'video',
      shareTime: '2025-10-22 14:20',
      status: 'expiring_soon', // 即将过期
      visitCount: 8,
      shareUrl: 'https://example.com/share/stu901'
    },
    {
      fileId: '8',
      fileName: '音乐合集',
      fileType: 'folder',
      shareTime: '2025-10-20 09:15',
      status: 'expired', // 已过期
      visitCount: 3,
      shareUrl: 'https://example.com/share/vwx234'
    }
  ]
  
  shareList.value = mockData
  pagination.total = mockData.length
  loading.value = false
}

// ==================== 状态管理 ====================
// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'active':
      return 'success'
    case 'expiring_soon':
      return 'warning'
    case 'expired':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'active':
      return '永久有效'
    case 'expiring_soon':
      return '23小时后过期'
    case 'expired':
      return '已过期'
    default:
      return '未知状态'
  }
}

// ==================== 选择操作 ====================
// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

// ==================== 操作功能 ====================
// 复制分享链接
const handleCopyLink = async (item) => {
  try {
    await navigator.clipboard.writeText(item.shareUrl)
    ElMessage.success('分享链接已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = item.shareUrl
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('分享链接已复制到剪贴板')
  }
}

// 取消单个分享
const handleCancelShare = (item) => {
  ElMessageBox.confirm(
    `确定要取消 "${item.fileName}" 的分享吗？取消后分享链接将失效。`,
    '取消分享',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    // 模拟处理延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 从列表中移除该项
    const index = shareList.value.findIndex(share => share.fileId === item.fileId)
    if (index !== -1) {
      shareList.value.splice(index, 1)
      pagination.total = shareList.value.length
    }
    
    ElMessage.success('分享已取消')
  }).catch(() => {
    // 用户取消操作
  })
}

// 批量取消分享
const handleBatchCancel = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择要取消分享的文件')
    return
  }

  const activeItems = selectedItems.value.filter(item => item.status === 'active' || item.status === 'expiring_soon')
  if (activeItems.length === 0) {
    ElMessage.warning('选中的文件中没有有效的分享')
    return
  }

  ElMessageBox.confirm(
    `确定要取消选中的 ${activeItems.length} 个文件的分享吗？`,
    '批量取消分享',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    // 模拟处理延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 从列表中移除这些项
    activeItems.forEach(item => {
      const index = shareList.value.findIndex(share => share.fileId === item.fileId)
      if (index !== -1) {
        shareList.value.splice(index, 1)
      }
    })
    
    pagination.total = shareList.value.length
    selectedItems.value = []
    
    ElMessage.success(`已取消 ${activeItems.length} 个文件的分享`)
  }).catch(() => {
    // 用户取消操作
  })
}


// ==================== 分页操作 ====================
// 处理页码变化
const handleCurrentChange = (current) => {
  pagination.current = current
  loadShareList()
}

// 处理页面大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadShareList()
}
</script>

<style lang="scss" scoped>
.netdisk-share {
  height: 100%;
  padding: 16px 18px;
  border-radius: 12px;
  background-color: #fff;

  // 顶部提示
  .share-tip {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    margin-bottom: 18px;
    background-color: #f0f9ff;
    border: 1px solid #bae6fd;
    border-radius: 8px;
    color: #0369a1;
    font-size: 14px;

    .tip-icon {
      margin-right: 8px;
      color: #0284c7;
    }
  }

  // 头部区域
  .share-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .share-stats {
      .stat-item {
        .stat-label {
          font-size: 16px;
          font-weight: 500;
          margin-right: 12px;
        }

        .stat-count {
          color: #666;
          font-size: 14px;

          .highlight {
            color: #4775F5;
            margin: 0 3px;
          }
        }
      }
    }

    .share-actions {
      display: flex;
      align-items: center;
      gap: 16px;

    }
  }

  // 内容区域
  .share-content {
    min-height: 400px;

    // 表格视图
    .share-table {
      .file-info {
        display: flex;
        align-items: center;

        :deep(.item-cover-img) {
          width: 20px !important;
          height: 20px !important;
        }

        .file-name {
          margin-left: 8px;
        }
      }

      .action-buttons {
        display: flex;
        gap: 8px;

        .expired-text {
          color: #909399;
          font-size: 14px;
          line-height: 32px;
        }
      }
    }
  }

  // 分页
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

// 响应式设计
@media screen and (max-width: 768px) {
  .netdisk-share {
    .share-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
    }
  }
}
</style>
